﻿using CpsyV2Web.DataAccess;
using Longbow.ExceptionManagement;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace CpsyV2Web.Controllers
{
    public class UploadController : ApiController
    {
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public UploadFileObject Post()
        {
            var fileName = string.Empty;
            var files = HttpContext.Current.Request.Files;
            if (files.Count > 0)
            {
                var webSiteUrl = DictHelper.RetrieveIconFolderPath();
                fileName = string.Format("Exam{0}-{1}", DateTime.Now.ToString("HHmmssfff"), files[0].FileName);
                var fileUrl = string.Format("{0}{1}", webSiteUrl, fileName);
                var filePath = HttpContext.Current.Server.MapPath(fileUrl);
                try
                {
                    var fileFolder = Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(fileFolder)) Directory.CreateDirectory(fileFolder);
                    files[0].SaveAs(filePath);
                }
                catch (Exception ex)
                {
                    var nv = new NameValueCollection();
                    nv.Add("UpLoadFileName", filePath);
                    ExceptionManager.Publish(ex, nv);
                }
            }
            return new UploadFileObject() { initialPreview = new List<string>() { string.Format("../content/images/exam/{0}", fileName) }, initialPreviewConfig = new List<UploadFilePreviewConfig>() { new UploadFilePreviewConfig() { caption = fileName, size = files[0].ContentLength, key = fileName } }, append = HttpContext.Current.Request.Form["append"] == "true" };
        }

        /// <summary>
        /// 
        /// </summary>
        public class UploadFileObject
        {
            /// <summary>
            /// 
            /// </summary>
            public List<string> initialPreview { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<UploadFilePreviewConfig> initialPreviewConfig { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public bool append { get; set; }
        }
        /// <summary>
        /// 
        /// </summary>
        public class UploadFilePreviewConfig
        {
            /// <summary>
            /// 
            /// </summary>
            public string caption { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int size { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string key { get; set; }
        }
    }
}
